package com.huang.wangpan.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huang.wangpan.dto.FileIm;
import com.huang.wangpan.dao.UserFileDao;
import com.huang.wangpan.dao.UserDao;
import com.huang.wangpan.vo.UserFile;
import com.huang.wangpan.utils.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class GetDataService {
    @Autowired
    UserFileDao userFileDao;
    @Autowired
    PathAnalysis pathAnalysis;
    @Autowired
    VoToBean voToBean;
    @Autowired
    ResultData resultData;
    @Autowired
    GetIcon getIcon;
    @Autowired
    UserDao userDao;

    @Value("${file.warehouse}")
    private String fileWarehouse;

    private static final Logger logger = LoggerFactory.getLogger(GetDataService.class);

    public void deleteFile(HttpServletRequest request, String path) {

        String token = CommonUtils.loadToken(request);
        String name = userDao.selectNameByToken(token);
        List<UserFile> ufs = userFileDao.searchByName(name);

        for (int i = 0; i < ufs.size(); i++) {
            UserFile temp = ufs.get(i);
            String paths = temp.getVirtualpath();
            if (paths.startsWith(path)) {
                userFileDao.deleteFile(0, paths, name);
            }
        }
    }

    // 判断是否是新文件
    public Boolean isSameName(HttpServletRequest request, String path, String filename) {
        String token = CommonUtils.loadToken(request);
        String name = userDao.selectNameByToken(token);
        List<UserFile> ufs = userFileDao.searchByName(name);
        for (int i = 0; i < ufs.size(); i++) {
            UserFile temp = ufs.get(i);
            String paths = temp.getVirtualpath();
            if (paths.startsWith(path + filename)) {
                String temps = paths.substring(path.length());
                int index = temps.indexOf('/');
                String test = "";
                if (index != -1) {
                    test = temps.substring(0, index);
                } else {
                    test = temps;
                }
                logger.info("test= {}", test);
                if (test.equals(filename)) {
                    logger.info("filename= {}", filename);
                    return true;
                }
            }
        }
        return false;
    }

    public void rename(HttpServletRequest request, String path, String newname, String filename) {
        String token = CommonUtils.loadToken(request);
        String name = userDao.selectNameByToken(token);
        List<UserFile> ufs = userFileDao.searchByName(name);
        for (int i = 0; i < ufs.size(); i++) {
            UserFile temp = ufs.get(i);
            String paths = temp.getVirtualpath();
            if (paths.startsWith(path + filename)) {
                String temps = paths.substring(path.length(), paths.length());
                int index = temps.indexOf('/');
                String end = "";
                if (index != -1) {
                    end = temps.substring(index, temps.length());
                }
                String newpath = path + newname + end;
                logger.info("newpath---->", newpath);
                userFileDao.updateFilename(newpath, paths, name);
            }
        }
    }

    public ResultData CreateNewFile(HttpServletRequest request, String newpath, String fileName, int page, String isfloder) {
        Boolean flag = true;
        String token = CommonUtils.loadToken(request);
        String name = userDao.selectNameByToken(token);
        List<UserFile> ufs = userFileDao.searchByName(name);
        List<FileIm> fms = pathAnalysis.getNewFloder(ufs, newpath, page);
        FileIm newfileim = new FileIm();
        newfileim.setFilename(fileName);
        if ("false".equals(isfloder)) {// 文件
            newfileim.setIconsign(getIcon.Icons(fileName));
            // 判断文件大小
            String fileSize = findFileSize(FileUtil.getCurrentPath() + fileWarehouse + fileName);
            newfileim.setFilesize(fileSize);
        } else {
            newfileim.setFilesize("-");
            newfileim.setIconsign("#icon-folder");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(new Date());
        newfileim.setMtime(format);
        if (!isSameName(request, newpath, fileName)) {
            fms.add(newfileim);
            flag = false;
        }
        UserFile uf = voToBean.fileimToUserFile(newfileim, name, newpath);
        userFileDao.insert(uf);
        JSONObject message = new JSONObject();
        JSONArray data = new JSONArray();
        for (int i = 0; i < fms.size(); i++) {
            FileIm temp = fms.get(i);
            JSONObject tempj = new JSONObject();
            tempj.put("filesize", temp.getFilesize());
            tempj.put("filename", temp.getFilename());
            tempj.put("date", temp.getMtime());
            tempj.put("iconsign", temp.getIconsign());
            data.add(tempj);
        }
        JSONObject msg = new JSONObject();
        msg.put("Catalogue", page);
        msg.put("currentpath", newpath);
        msg.put("flag", flag);
        message.put("code", 0);
        message.put("msg", msg);
        message.put("data", data);
        resultData.setData(message);
        return resultData;
    }


    /**
     * 根据文件计算文件大小
     *
     * @param realPath
     * @return
     */
    private String findFileSize(String realPath) {
        File file = new File(realPath);
        return new ByteUnitConversion().readableFileSize(file.length());
    }

}
